package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("category")
@RestController
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    /**
     * 添加
     * @param category
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("page")
    public R<Page<Category>> page() {
        //创建分页对象
        Page<Category> pageInfo = new Page<>();
        //创建条件对象
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        //分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据员工删除
     */
    @DeleteMapping
    public R<String> remove(Long id) {
        categoryService.remove(id);
        return R.success("删除成功");
    }

    /**
     * 修改员工
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据条件分类查询
     */
    @GetMapping("list")
    public R<List<Category>> list(Integer type){

        QueryWrapper<Category> queryWrap = new QueryWrapper<>();
        queryWrap.eq(type!=null,"type",type).orderByAsc("sort");
        List<Category> list = categoryService.list(queryWrap);

        return R.success(list);
    }


}
